<template>
  <div>
    <el-upload
      v-model:file-list="localFileList"
      class="avatar-uploader"
      list-type="picture-card"
      :action="UPLOAD_URL"
      :accept="'image/*'"
      :on-success="handleUploadSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <el-icon>
        <Plus />
      </el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from "@element-plus/icons-vue";
import { UPLOAD_URL } from "@/constants/BaseConstants";
import { computed, ref, watch } from "vue";
import { cdn_url, remove_cdn_url } from "@/utils/common";
import { UploadFile, UploadFiles, UploadUserFile } from "element-plus";

defineOptions({
  name: "多个图片上传"
});

const props = defineProps({
  value: {}
});
const fileList = ref([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

watch(
  () => props.value,
  newValue => {
    fileList.value = newValue as [];
  }
);
const localFileList = computed({
  get() {
    return fileList.value.map(item => {
      return {
        url: cdn_url(item.url),
        name: item.name
      };
    });
  },
  set() {}
});

/**
 * 文件上传成功
 * @param response
 * @param uploadFile
 * @param uploadFiles
 */
function handleUploadSuccess(
  response: any,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) {
  uploadFile.url = response.url;
  uploadFile.name = response.original_name;
  emits(
    "updateImageUrl-event",
    uploadFiles.map(item => {
      return {
        url: remove_cdn_url(item.url),
        name: item.name
      };
    })
  );
}

/**
 * 文件移除
 * @param _
 * @param uploadFiles
 */
function handleRemove(_: UploadFile, uploadFiles: UploadFiles) {
  emits(
    "updateImageUrl-event",
    uploadFiles.map(item => {
      return {
        url: remove_cdn_url(item.url),
        name: item.name
      };
    })
  );
}

function handlePictureCardPreview(uploadFile: UploadFile) {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
}

const emits = defineEmits(["updateImageUrl-event"]);
</script>
